
#include <OpenCV/OpenCV.h>
#include <cassert>
#include <iostream>
#include <OpenCV/cv.h>
#include <OpenCV/cxcore.h>
#include <OpenCV/highgui.h>
// Blobs
#include <Blob.h>
#include <BlobResult.h>

using namespace std;

int main (int argc, char * const argv[]) 
{
	CBlobResult blobs;
	// create all necessary instances
    cvNamedWindow ("Blob", CV_WINDOW_AUTOSIZE);
	cvNamedWindow ("Gray", CV_WINDOW_AUTOSIZE);
    //CvCapture * camera = cvCreateCameraCapture (CV_CAP_ANY);
	CvCapture * camera = cvCaptureFromCAM(CV_CAP_ANY);
	//CvCapture * camera = cvCaptureFromAVI("/Repositories/touchlib/tests/hard-5point.avi");
	//CvCapture * camera = cvCaptureFromFile("/Repositories/touchlib/tests/hard-5point.avi");
	//double fps = cvGetCaptureProperty(camera, CV_CAP_PROP_FPS);
	//cvSetCaptureProperty(camera,CV_CAP_PROP_FPS, 30.0);
	//printf("FPS: %f\n",fps);
	//CvCapture * camera = cvCaptureFromAVI("/Repositories/touchlib/tests/simple-2point.avi");
    // you do own an iSight, don't you ?!?
    if (! camera)
        abort ();

    // get an initial frame and duplicate it for later work
    IplImage *  current_frame = cvQueryFrame (camera);
	IplImage *  gray_image    = cvCreateImage(cvSize (current_frame->width, current_frame->height), IPL_DEPTH_8U, 1);
    IplImage *  binary_image  = cvCreateImage(cvSize (current_frame->width, current_frame->height), IPL_DEPTH_8U, 1);    
    
	// as long as there are images ...
    while (current_frame = cvQueryFrame (camera))
    {
        // convert to gray and downsize
        cvCvtColor (current_frame, gray_image, CV_BGR2GRAY);
        cvThreshold(gray_image, binary_image, 170, 255, CV_THRESH_BINARY_INV);
		
		
		blobs = CBlobResult( binary_image, NULL, 50, true );
		// mark the blobs on the image
		int i;
		// delare a single blob
		CBlob Blob;
		// some vars
		int iMaxx, iMinx, iMaxy, iMiny, iMeanx, iMeany;
		// for each blob
		for  (i=0; i<blobs.GetNumBlobs(); ++i)
		{
			// get the blob info
			Blob = blobs.GetBlob(i);
			// get max, and min co-ordinates
			iMaxx=Blob.MaxX();
			iMinx=Blob.MinX();
			iMaxy=Blob.MaxY();
			iMiny=Blob.MinY();
			// find the average of the blob (i.e. estimate its centre)
			iMeanx=(iMinx+iMaxx)/2;
			iMeany=(iMiny+iMaxy)/2;
			// mark centre
			cvLine( current_frame, cvPoint(iMeanx, iMeany), cvPoint(iMeanx, iMeany), CV_RGB(50, 50 , 50), 4, 8, 0 );
			// mark box around blob
			cvRectangle( current_frame, cvPoint(iMinx , iMiny ), cvPoint ( iMaxx, iMaxy ), CV_RGB(150, 150, 150), 1, 8, 0);
			// print the blob centres
			//printf("\n%d, X: %d, Y: %d\n", i, iMeanx, iMeany);
		}// each blob
	
        // just show the image
        
		cvShowImage ("Blob", binary_image);
        cvShowImage ("Gray", current_frame);
		
        // wait a tenth of a second for keypress and window drawing
        int key = cvWaitKey (100);
        if (key == 'q' || key == 'Q')
            break;
    }
    
    // be nice and return no error
    return 0;
}
